package eu.vranckaert.workRegistrationWidget.util;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.widget.RemoteViews;
import eu.vranckaert.workRegistrationWidget.R;
import eu.vranckaert.workRegistrationWidget.activities.RegisterWorkActivity;
import eu.vranckaert.workRegistrationWidget.activities.ResultsActivity;
import eu.vranckaert.workRegistrationWidget.domain.TimeRegistration;
import eu.vranckaert.workRegistrationWidget.service.WidgetLayoutBuilderService;
import eu.vranckaert.workRegistrationWidget.widgetProvider.WorkRegistrationWidgetProvider;

/**
 * @Author Dirk Vranckaert
 * Date: 28-apr-2010
 * Time: 23:04:59
 */
public class WidgetUpdater {
    private static final int WIDGET = R.layout.work_registration_widget;

    private static RemoteViews getRemoteView(Context context) {
        return new RemoteViews(context.getPackageName(), WIDGET);
    }

    private static void updateView(Context context, RemoteViews updatedView) {
        ComponentName cn = new ComponentName(context, WorkRegistrationWidgetProvider.class);
        AppWidgetManager mgr = AppWidgetManager.getInstance(context);
		mgr.updateAppWidget(cn, updatedView);
    }

    public static void updateWidget(Context context, TimeRegistration timeRegistration, WidgetLayoutBuilderService widgetLayoutBuilderService) {
        RemoteViews remoteView = WidgetUpdater.getRemoteView(context);

        //Update text on widget
		remoteView.setTextViewText(R.id.regText, widgetLayoutBuilderService.getRegistrationText(context, timeRegistration));
        remoteView.setCharSequence(R.id.regButton, "setText", widgetLayoutBuilderService.getRegistrationButtonText(context, timeRegistration));

        //Set intent on buttons
        // Create an Intent to launch RegisterWorkActivity
        Intent regIntent = new Intent(context, RegisterWorkActivity.class);
        PendingIntent registrationIntent = PendingIntent.getActivity(context, 0, regIntent, 0);
        // Create an Intent to launch ResultsActivity
        Intent resIntent = new Intent(context, ResultsActivity.class);
        PendingIntent resultsIntent = PendingIntent.getActivity(context, 0, resIntent, 0);
        // Get the layout for the App Widget and attach an on-click listener to the buttons:
        // regButton
        // regResults
        remoteView.setOnClickPendingIntent(R.id.regButton, registrationIntent);
        remoteView.setOnClickPendingIntent(R.id.regResults, resultsIntent);

        WidgetUpdater.updateView(context, remoteView);
    }
}
